# _*_ coding:utf-8 _*_
# @Time :2022/8/12 10:18
# @File :  producer_yuqidong.py
# @Author :QiKangwei
import copy
import json
import logging
# from scapy.all import *
import threading,os,traceback
import queue

import pymysql

from detecter import settings

# import threading,os,traceback,time
# from threading import Thread
logger = logging.getLogger('pojie_A10.producer_set_A10')
set_yichang_time = 200


class SampleProducer_set_A10(threading.Thread):
    __instance = None

    def __init__(self, ip, port, com, baud):
        super().__init__()
        self.setName('SampleProducer_set_A10')
        self.__running = threading.Event()  # 用于停止线程的标识
        self.__data_bytes = bytearray()  # 全局字节数组,串口数据缓冲区
        self.__data_bytes_part = bytearray()  # 全局字节数组,串口数据缓冲区
        # ##############   操作板相关   ###############
        self.Verification_List = ["02000900", "02008802"]
        self.Verification_List_del_len = [18 * 2, 1296 * 2]
        # 操作板设定参数
        self.set_field_dictionary = {}  # 这里的设置值json文件可改动，像焕发项目的json可配置文件一样
        self.set_field_dictionary_supply = {}  # 这里的设置值json文件可改动，像焕发项目的json可配置文件一样
        self.q_set=queue.Queue(30000)
        self.start_data = bytes()
        self.MACHINE_CODE=settings.MACHINE_CODE

        # ##############   分类采集   ###############
        self.conn = None
        self.collection = None
        self.thread_collection = None
        self.stop_sniffing = False

        # ##############   网口采集传输数据   ###############
        self.ip = ip
        self.port = port

        # ##############   串口采集传输数据   ###############
        self.com = com
        self.baud = baud

    @classmethod
    def new_instance(cls, ip, port, com, baud):
        # por1 = 51501  # 控制板——设定数据
        # por2 = 52501  # 操作板——实时数据
        cls.__instance = SampleProducer_set_A10(ip, port, com, baud)
        return cls.__instance

    @classmethod
    def get_instance(cls):
        return cls.__instance

    def begin(self):
        if not self.is_alive():
            self.__running.set()
            self.setDaemon(False)  # 不设置守护线程, 就算websocket挂了也继续收集数据,处理数据, 存入临时文件中, 直到停止本工单才算停止此线程
            self.start()

    # 其实这个函数可以不写，项目中期的时候提出 采集线程一直工作
    def stop(self):
        if self.is_alive():
            if self.thread_collection:
                self.thread_collection.join()

            self.__running.clear()  # 设置为False

    def run(self):
        sql_flag = True
        while sql_flag:
            try:
                self.set_field_dictionary_supply = self.cha_xun(self.MACHINE_CODE)  # 线程启动时就将其读出来
                if self.set_field_dictionary_supply != "数据库查询失败,请检查数据库是否可以访问":
                    sql_flag = False
                else:
                    raise ValueError("数据库查询失败,请检查数据库是否可以访问")
            except Exception as e:
                self.q_set.queue.clear()
                logger.error(e)

        data_flag = False
        pressure_size = 8  # 用作判别、确认字段信息的长度
        frame_rate = 5  # 机台采集数据的频率(计算周期字段的数据频率)，1s有多少帧数据传过来   此线程只采集设置值，频率暂定为5Hz
        count = 1024 * 16  # 返回接收缓存中的字节数
        while self.__running.is_set():
            while self.q_set.qsize()>=1:
                if self.q_set.qsize()>10000:
                    logger.info(f'self.q_set.qsize出现数据累积，已达到{self.q_set.qsize()}')
                if not data_flag:
                    logger.info("采集控制板设定值，有无工单不影响！！！")
                    data_flag = True
                data_bytes=self.q_set.get()
                frame_bytes = data_bytes[0:int(pressure_size / 2)].hex().upper()
                whether_to_parse, del_size = self.verify_dictionary(frame_bytes, self.Verification_List, self.Verification_List_del_len)
                if del_size == self.Verification_List_del_len[1]:# or 0<len(self.start_data)<1296
                    # with open("//usr//local//src//webroot//detecter//data//test108.txt", "a+") as f:  ##不要在这里进行写操作，耗时严重，会严重丢帧！！！！！！！！！！！
                    #     f.write(data_bytes.hex().upper())
                    #     f.write("哈哈哈哈哈\n")
                    #     print("成功写入！",'长度：',len(data_bytes))
                    logger.info('捕获到开机数据！')
                    # if len(data_bytes)>= 1296:
                    #     data_bytes = copy.deepcopy(self.start_data)[:1296]
                    #     self.start_data = bytes()
                    #     whether_to_parse, del_size = True, 1296 * 2
                    #     logger.info("开机启动完整数据捕获成功！！！")
                    #     logger.info(data_bytes)
                    # self.start_data += data_bytes
                    # if len(self.start_data)>= 1296:
                    #     data_bytes = copy.deepcopy(self.start_data)[:1296]
                    #     self.start_data = bytes()
                    #     whether_to_parse, del_size = True, 1296 * 2
                    #     logger.info("开机启动完整数据捕获成功！！！")
                    #     logger.info(data_bytes)
                # 若标识字段在所要解析的列表中时，根据该标识拿到字节长度即是后面所删除的字长度
                if whether_to_parse:
                    frame_bytes = data_bytes[0:int(del_size / 2)].hex().upper()  # 拿到对应字段信息长度数据
                    # 数据过滤、异或校验
                    if self.XOR_verification(frame_bytes[4:-6]) == frame_bytes[-6:-4]:

                        # 将数据添加到指定列表
                        try:
                            self.add_data_to_list(frame_bytes, pressure_size)
                        except:
                            logger.info(traceback.format_exc())

                        # 后存储
                        if self.set_field_dictionary != {} and self.set_field_dictionary != {
                            'a': 'a'}:
                            for key, value in self.set_field_dictionary.items():
                                # 检查值是否为整数或浮点数
                                if isinstance(value, (int, float)):
                                    if value > 60000:
                                        self.set_field_dictionary[key] = 0
                            self.set_field_dictionary_supply.update(self.set_field_dictionary)
                            self.update(self.set_field_dictionary_supply, self.MACHINE_CODE)
                            logger.info(f'更新值成功,{self.set_field_dictionary}')
                            self.set_field_dictionary = {}
                    else:
                        del_size = 1  # 帧数据校验错误
                else:
                    pass




    # 异或校验
    def XOR_verification(self, str1):
        res = None
        for x in range(0, len(str1), 2):
            hex_str = int("0x" + str1[x:x + 2], 16)  # 把16进制转10进制
            if x:
                # 第一个
                res ^= hex_str
            else:
                res = hex_str ^ 0
        ret = hex(res).upper()[2:]
        if len(ret) != 2:
            ret = '0' * (2 - len(ret)) + ret
        return ret

    def add_data_to_list(self, frame_bytes, pressure_size):

        # 去找对应方法解析
        if frame_bytes[:pressure_size] == "02000900":  # 设置字段信息
            self.set_field_dictionary = self.set_value_information(frame_bytes, self.set_field_dictionary)

        # 解析开机数据
        elif frame_bytes[:16] == "02008802000B3233":  # 解析开机数据A
            self.set_field_dictionary = self.parsing_startup_data_A(frame_bytes, self.set_field_dictionary)
        elif frame_bytes[:16] == "02008802000D3333":  # 解析开机数据B
            self.set_field_dictionary = self.parsing_startup_data_B(frame_bytes, self.set_field_dictionary)
        elif frame_bytes[:16] == "02008802001F3234":  # 解析开机数据C
            self.set_field_dictionary = self.parsing_startup_data_C(frame_bytes, self.set_field_dictionary)

    # 处理设置值字段信息
    # 0200053336————设置字段信息（有更改即发送数据，24位）
    @staticmethod
    def set_value_information(frame_bytes, set_field_dictionary):
        # 高低位交换
        gao = frame_bytes[24:26]
        di = frame_bytes[26:28]
        frame_bytes = list(frame_bytes)
        frame_bytes[24:26], frame_bytes[26:28] = di, gao
        frame_bytes = "".join(frame_bytes)

        verify_length = 16
        pipei_shuju = frame_bytes[:8] + frame_bytes[12:20]
        # 分种类的
        a = ["0200090032337A02", "0200090032338F00", "020009003333C300", "0200090033331501",
             "020009003233AC01", "020009003233C000", "020009003233C200", "020009003233C300",
             "020009003233C100", "020009003233D100", "020009003233D200", "020009003233E000",
             "020009003233E200", "020009003233E300", "020009003233E100", "020009003233F100",
             "020009003233F200", "0200090032330001", "0200090032330201", "0200090032330301",
             "0200090032330101", "0200090032331101", "0200090032331201",
             ]

        # 1位小数的
        b = ["020009003234C000", "020009003234C100", "020009003234C200", "020009003234C300",
             "020009003234C400", "020009003234C500", "020009003234C600", "020009003234C700", "020009003234C800",
             "0200090033339100", "0200090033339400", "0200090033339900", "0200090033331100",
             "0200090033331400", "0200090033331700", "0200090033331A00", "0200090033331D00",
             "0200090033332000", "0200090033332300", "0200090033332600", "0200090033332900",
             "0200090033332C00", "0200090033332F00", "0200090032335102", "0200090032335502",
             "0200090032335902", "0200090032335D02", "0200090032336102", "0200090032336502",
             "0200090032338100", "0200090032338400", "0200090032338700", "0200090032338A00",
             "0200090032338D00", "020009003333B100", "020009003333B400", "020009003333B700",
             "020009003333BA00", "020009003333BD00", "0200090032335300", "0200090032335200",
             "0200090032335700", "0200090032335600", "0200090032335B00", "0200090032335A00",
             "0200090032335F00", "0200090032335E00", "0200090032336300", "0200090032336200",
             "0200090033331101", "0200090033331301", "0200090033331701", "0200090032336C00",
             "020009003233A201", "020009003233A101", "020009003233A501", "020009003233A401",
             "020009003233A801", "020009003233A701", "020009003233AB01", "020009003233AA01",
             "020009003233C600", "020009003233D500", "020009003233E600", "020009003233F500",
             "0200090032330601", "0200090032331501", "0200090032337902"
             ]

        # 2位小数的
        c = ["0200090033339B00", "0200090033339C00", "020009003033EC01", "0200090032335202",
             "0200090032335602", "0200090032335A02", "0200090032335E02", "0200090032336202",
             "0200090032336602", "0200090033337400", "020009003233BA00", "020009003233B800",
             "0200090032336A00", "020009003233AE01", "020009003233AF01", "020009003233C700",
             "020009003233D600", "020009003233E700", "020009003233F600", "0200090032330701",
             "0200090032331601", "0200090033331200"
             ]

        # 16进制直接转换为10进制的
        d = ["0200090033339000", "0200090033339300", "0200090033339800", "0200090033331000",
             "0200090033331600", "0200090033331C00", "0200090033332200", "0200090033332800",
             "0200090033332E00", "0200090032335002", "0200090032335402", "0200090032335802",
             "0200090032335C02", "0200090032336002", "0200090032336402",
             "0200090032337802", "0200090032338000", "0200090032338300",
             "0200090032338600", "0200090032338900", "0200090032338C00", "020009003333B000",
             "020009003333B300", "020009003333B600", "020009003333B900", "020009003333BC00",
             "0200090032335000", "0200090032335100", "0200090032335400", "0200090032335500",
             "0200090032335800", "0200090032335900", "0200090032335C00", "0200090032335D00",
             "0200090032336000", "0200090032336100", "0200090033331001", "020009003233A001",
             "020009003233A301", "020009003233A601", "020009003233A901", "020009003233AD01",
             "020009003233C500", "020009003233C800", "020009003233D400", "020009003233D700",
             "020009003233E500", "020009003233E800", "020009003233F400", "020009003233F700",
             "0200090032330501", "0200090032330801", "0200090032331401", "0200090032331701",
             ]

        if pipei_shuju in d:  # 普通的
            set_field_dictionary[pipei_shuju] = int(frame_bytes[24:28], 16)

        elif pipei_shuju in a:  # 分种类的
            if pipei_shuju == "0200090032337A02":
                set_field_dictionary[pipei_shuju] = {"0000": "位置", "0001": "时间", "0002": "压力"}[
                    frame_bytes[24:28]]
            elif pipei_shuju == "0200090032338F00":
                set_field_dictionary[pipei_shuju] = {"0000": "不用", "0001": "使用"}[
                    frame_bytes[24:28]]
            elif pipei_shuju == "020009003333C300":
                set_field_dictionary[pipei_shuju] = \
                    {"0000": "不用", "0001": "托模", "0002": "中子A", "0003": "中子B", "0004": "中子C", "0005": "中子D",
                     "0006": "中子E", "0007": "中子F", "0008": "中子G", "0009": "中子H"}[
                        frame_bytes[24:28]]
            elif pipei_shuju == "0200090033331501":
                set_field_dictionary[pipei_shuju] = {"0000": "储料后", "0001": "冷却后"}[
                    frame_bytes[24:28]]
            elif pipei_shuju == "020009003233AC01":
                set_field_dictionary[pipei_shuju] = {"0000": "停留", "0001": "定次", "0002": "振动"}[
                    frame_bytes[24:28]]
            elif pipei_shuju in ["020009003233C000", "020009003233E000", "0200090032330001"]:
                set_field_dictionary[pipei_shuju] = {"0000": "不用", "0001": "中子", "0002": "绞牙"}[
                    frame_bytes[24:28]]
            elif pipei_shuju in ["020009003233C200", "020009003233E200", "0200090032330201"]:
                set_field_dictionary[pipei_shuju] = {"0000": "行程", "0001": "时间", "0002": "行程+时间"}[
                    frame_bytes[24:28]]
            elif pipei_shuju in ["020009003233C300", "020009003233E300", "0200090032330301"]:
                set_field_dictionary[pipei_shuju] = {"0000": "关始", "0001": "中途", "0002": "关终"}[
                    frame_bytes[24:28]]
            elif pipei_shuju in ["020009003233C100", "020009003233E100", "0200090032330101"]:
                set_field_dictionary[pipei_shuju] = {"0000": "保持", "0001": "不保持"}[
                    frame_bytes[24:28]]
            elif pipei_shuju in ["020009003233D100", "020009003233F100", "0200090032331101"]:
                set_field_dictionary[pipei_shuju] = {"0000": "行程", "0001": "时间", "0002": "行程+时间"}[
                    frame_bytes[24:28]]
            elif pipei_shuju in ["020009003233D200", "020009003233F200", "0200090032331201"]:
                set_field_dictionary[pipei_shuju] = {"0000": "开终", "0001": "中途", "0002": "开始"}[
                    frame_bytes[24:28]]

        elif pipei_shuju in b:  # 1位小数的
            set_field_dictionary[pipei_shuju] = round(
                int(frame_bytes[24:28], 16) / 10, 1)

        elif pipei_shuju in c:  # 2位小数的
            set_field_dictionary[pipei_shuju] = round(
                int(frame_bytes[24:28], 16) / 100, 2)

        return set_field_dictionary

    @staticmethod
    def verify_dictionary(frame_bytes, verification_List, verification_List_del_len):
        # 当前帧数据标识不在解析的列表中，直接跳过
        if frame_bytes not in verification_List:
            del_len = 1
            return False, del_len
        else:
            for i, j in enumerate(verification_List):
                if frame_bytes == j:
                    del_len = verification_List_del_len[i]
                    return True, del_len

    # 解析开机数据
    # 0205013333————设置字段信息（解析开机数据，2568位）
    @staticmethod
    def parsing_startup_data_A(frame_bytes, set_field_dictionary):
        # 分种类的
        a = ["0200090032337A02", "0200090032338F00", "0200090033331501",
             "020009003233AC01", "020009003233C000", "020009003233C200", "020009003233C300",
             "020009003233C100", "020009003233D100", "020009003233D200", "020009003233E000",
             "020009003233E200", "020009003233E300", "020009003233E100", "020009003233F100",
             "020009003233F200", "0200090032330001", "0200090032330201", "0200090032330301",
             "0200090032330101", "0200090032331101", "0200090032331201",
             ]

        # 1位小数的
        b = [
            "020009003234C400",
            "0200090033339100", "0200090033339400", "0200090033339900", "0200090033331100",
            "0200090033331400", "0200090033331700", "0200090033331A00", "0200090033331D00",
            "0200090033332000", "0200090033332300", "0200090033332600", "0200090033332900",
            "0200090033332C00", "0200090033332F00", "0200090032335102", "0200090032335502",
            "0200090032335902", "0200090032335D02", "0200090032336102", "0200090032336502",
            "0200090032338100", "0200090032338400", "0200090032338700", "0200090032338A00",
            "0200090032338D00", "020009003333B100", "020009003333B400", "020009003333B700",
            "020009003333BD00", "0200090032335300", "0200090032335200",
            "0200090032335700", "0200090032335600", "0200090032335B00", "0200090032335A00",
            "0200090032335F00", "0200090032335E00", "0200090032336300", "0200090032336200",
            "0200090033331301", "0200090032336C00",
            "020009003233A201", "020009003233A101", "020009003233A501", "020009003233A401",
            "020009003233A801", "020009003233A701", "020009003233AB01", "020009003233AA01",
            "020009003233C600", "020009003233D500", "020009003233E600", "020009003233F500",
            "0200090032330601", "0200090032337902"
        ]
        # 下面的这些标识字符串的后四位有重复值，先把这几个取出来，后续如果有需要，再将这几个值分别对照着添加进去，注意需要做区分。这些字段里面除了开模联动："020009003333C300"是从a里面拿出来的，其他的都是从b里面拿出来的。
        # 七段温度："020009003234C700",  五段温度："020009003234C500", 一段温度："020009003234C100",三段温度："020009003234C300", 射嘴温度："020009003234C000", 六段温度："020009003234C600",   二段温度："020009003234C200",八段温度："020009003234C800" ,这八个值在第三条开机数据里面，这里就先不取了
        # 开模四段速度(在第二条开机数据里面取，A里面就去掉)："020009003333BA00",
        # 储前射退距离："0200090033331701", 射退速度："0200090033331101", 中子C退速度："0200090032331501",开模联动："020009003333C300", 这四个值先暂时取出，看情况，再往里面添加。
        #
        # 2位小数的
        c = ["0200090033339B00", "0200090033339C00", "020009003033EC01", "0200090032335202",
             "0200090032335602", "0200090032335A02", "0200090032335E02", "0200090032336202",
             "0200090032336602", "0200090033337400", "020009003233BA00", "020009003233B800",
             "0200090032336A00", "020009003233AE01", "020009003233AF01", "020009003233C700",
             "020009003233D600", "020009003233E700", "020009003233F600", "0200090032330701",
             "0200090032331601", "0200090033331200"
             ]

        # 16进制直接转换为10进制的
        d = ["0200090033339000", "0200090033339300", "0200090033339800", "0200090033331000",
             "0200090033331600", "0200090033331C00", "0200090033332200", "0200090033332800",
             "0200090033332E00", "0200090032335002", "0200090032335402", "0200090032335802",
             "0200090032335C02", "0200090032336002", "0200090032336402",
             "0200090032337802", "0200090032338000", "0200090032338300",
             "0200090032338600", "0200090032338900", "0200090032338C00", "020009003333B000",
             "020009003333B300", "020009003333B600", "020009003333B900", "020009003333BC00",
             "0200090032335000", "0200090032335100", "0200090032335400", "0200090032335500",
             "0200090032335800", "0200090032335900", "0200090032335C00", "0200090032335D00",
             "0200090032336000", "0200090032336100", "0200090033331001", "020009003233A001",
             "020009003233A301", "020009003233A601", "020009003233A901", "020009003233AD01",
             "020009003233C500", "020009003233C800", "020009003233D400", "020009003233D700",
             "020009003233E500", "020009003233E800", "020009003233F400", "020009003233F700",
             "0200090032330501", "0200090032330801", "0200090032331401", "0200090032331701",
             ]
        # frame_bytes 是 2568 位  其中02是帧头  03是帧尾   05 01 33 33 00 00 是行标识

        # 0~4   4~8      8~12
        # 8 9   10 11    12 13   14 15   16 17   18 19   20 21      。。。    2566 2567
        # 0 1   2   3    4   5   6   7   8   9   10  11  12  13        减去8
        #   1       2        3       4       5       6       7      。。。         1280   加1 除以二
        # 0001   0002     0003    0004    0005    0006    0007      。。。         0500
        frame_bytes = frame_bytes[28:-4]
        list_A = [i for i in range(80, 100)] + [i for i in range(128, 142)] + [i for i in range(197, 201)] \
                 + [i for i in range(416, 428)] + [i for i in range(592, 595)] + [i for i in range(596, 599)] \
                 + [i for i in range(600, 603)] + [i for i in range(604, 607)] + [i for i in range(608, 611)] \
                 + [i for i in range(612, 615)] + [i for i in range(632, 635)]
        aa = [str(i[-4:])[-2:] + str(i[-4:])[:-2] for i in a]
        bb = [str(i[-4:])[-2:] + str(i[-4:])[:-2] for i in b]
        cc = [str(i[-4:])[-2:] + str(i[-4:])[:-2] for i in c]
        dd = [str(i[-4:])[-2:] + str(i[-4:])[:-2] for i in d]
        for i in list_A:
            try:
                hangbiaoshi_4 = i
                str_4 = str(frame_bytes[(i - 1) * 4:i * 4])
                corresponding_fields_i = str_4[-2:] + str_4[:-2]
                if hangbiaoshi_4 in [int(j[-4:], 16) for j in dd]:  # 普通的
                    set_field_dictionary[{int(str(k[-4:])[-2:] + str(k[-4:])[:-2], 16): k for k in d}[hangbiaoshi_4]] = int(corresponding_fields_i, 16)

                elif hangbiaoshi_4 in [int(j[-4:], 16) for j in aa]:  # 分种类的
                    hangbiaoshi = {int(str(k[-4:])[-2:] + str(k[-4:])[:-2], 16): k for k in a}[hangbiaoshi_4]
                    if hangbiaoshi == "0200090032337A02":
                        set_field_dictionary[hangbiaoshi] = {"0000": "位置", "0001": "时间", "0002": "压力"}[
                            corresponding_fields_i]
                    elif hangbiaoshi == "0200090032338F00":
                        set_field_dictionary[hangbiaoshi] = {"0000": "不用", "0001": "使用"}[
                            corresponding_fields_i]
                    elif hangbiaoshi == "020009003333C300":
                        set_field_dictionary[hangbiaoshi] = \
                            {"0000": "不用", "0001": "托模", "0002": "中子A", "0003": "中子B", "0004": "中子C", "0005": "中子D",
                             "0006": "中子E", "0007": "中子F", "0008": "中子G", "0009": "中子H"}[corresponding_fields_i]
                    elif hangbiaoshi == "0200090033331501":
                        set_field_dictionary[hangbiaoshi] = {"0000": "储料后", "0001": "冷却后"}[
                            corresponding_fields_i]
                    elif hangbiaoshi == "020009003233AC01":
                        set_field_dictionary[hangbiaoshi] = {"0000": "停留", "0001": "定次", "0002": "振动"}[
                            corresponding_fields_i]
                    elif hangbiaoshi in ["020009003233C000", "020009003233E000", "0200090032330001"]:
                        set_field_dictionary[hangbiaoshi] = {"0000": "不用", "0001": "中子", "0002": "绞牙"}[
                            corresponding_fields_i]
                    elif hangbiaoshi in ["020009003233C200", "020009003233E200", "0200090032330201"]:
                        set_field_dictionary[hangbiaoshi] = {"0000": "行程", "0001": "时间", "0002": "行程+时间"}[
                            corresponding_fields_i]
                    elif hangbiaoshi in ["020009003233C300", "020009003233E300", "0200090032330301"]:
                        set_field_dictionary[hangbiaoshi] = {"0000": "关始", "0001": "中途", "0002": "关终"}[
                            corresponding_fields_i]
                    elif hangbiaoshi in ["020009003233C100", "020009003233E100", "0200090032330101"]:
                        set_field_dictionary[hangbiaoshi] = {"0000": "保持", "0001": "不保持"}[
                            corresponding_fields_i]
                    elif hangbiaoshi in ["020009003233D100", "020009003233F100", "0200090032331101"]:
                        set_field_dictionary[hangbiaoshi] = {"0000": "行程", "0001": "时间", "0002": "行程+时间"}[
                            corresponding_fields_i]
                    elif hangbiaoshi in ["020009003233D200", "020009003233F200", "0200090032331201"]:
                        set_field_dictionary[hangbiaoshi] = {"0000": "开终", "0001": "中途", "0002": "开始"}[
                            corresponding_fields_i]

                elif hangbiaoshi_4 in [int(j[-4:], 16) for j in bb]:  # 1位小数的
                    hangbiaoshi = {int(str(k[-4:])[-2:] + str(k[-4:])[:-2], 16): k for k in b}[hangbiaoshi_4]
                    set_field_dictionary[hangbiaoshi] = round(int(corresponding_fields_i, 16) / 10, 1)

                elif hangbiaoshi_4 in [int(j[-4:], 16) for j in cc]:  # 2位小数的
                    hangbiaoshi = {int(str(k[-4:])[-2:] + str(k[-4:])[:-2], 16): k for k in c}[hangbiaoshi_4]
                    set_field_dictionary[hangbiaoshi] = round(int(corresponding_fields_i, 16) / 100, 2)
            except:
                continue

        return set_field_dictionary

    # 解析开机数据
    # 0205013333————设置字段信息（解析开机数据，2568位）
    @staticmethod
    def parsing_startup_data_B(frame_bytes, set_field_dictionary):
        # 分种类的
        a = ["0200090032337A02", "0200090032338F00", "0200090033331501",
             "020009003233AC01", "020009003233C000", "020009003233C200", "020009003233C300",
             "020009003233C100", "020009003233D100", "020009003233D200", "020009003233E000",
             "020009003233E200", "020009003233E300", "020009003233E100", "020009003233F100",
             "020009003233F200", "0200090032330001", "0200090032330201", "0200090032330301",
             "0200090032330101", "0200090032331101", "0200090032331201",
             ]  # C300是重复的  "020009003333C300"  "020009003233C300"

        # 1位小数的
        b = [
            "020009003234C400", "020009003333BA00"
                                "0200090033339100", "0200090033339400", "0200090033339900", "0200090033331100",
            "0200090033331400", "0200090033331700", "0200090033331A00", "0200090033331D00",
            "0200090033332000", "0200090033332300", "0200090033332600", "0200090033332900",
            "0200090033332C00", "0200090033332F00", "0200090032335102", "0200090032335502",
            "0200090032335902", "0200090032335D02", "0200090032336102", "0200090032336502",
            "0200090032338100", "0200090032338400", "0200090032338700", "0200090032338A00",
            "0200090032338D00", "020009003333B100", "020009003333B400", "020009003333B700",
            "020009003333BD00", "0200090032335300", "0200090032335200",
            "0200090032335700", "0200090032335600", "0200090032335B00", "0200090032335A00",
            "0200090032335F00", "0200090032335E00", "0200090032336300", "0200090032336200",
            "0200090033331301", "0200090032336C00",
            "020009003233A201", "020009003233A101", "020009003233A501", "020009003233A401",
            "020009003233A801", "020009003233A701", "020009003233AB01", "020009003233AA01",
            "020009003233C600", "020009003233D500", "020009003233E600", "020009003233F500",
            "0200090032330601", "0200090032337902"
        ]
        # 下面的这些标识字符串的后四位有重复值，先把这几个取出来，后续如果有需要，再将这几个值分别对照着添加进去，注意需要做区分。这些字段里面除了开模联动："020009003333C300"是从a里面拿出来的，其他的都是从b里面拿出来的。
        # 七段温度："020009003234C700",  五段温度："020009003234C500", 一段温度："020009003234C100",三段温度："020009003234C300", 射嘴温度："020009003234C000", 六段温度："020009003234C600",   二段温度："020009003234C200",八段温度："020009003234C800" ,这八个值在第三条开机数据里面，这里就先不取了
        # 储前射退距离："0200090033331701", 射退速度："0200090033331101", 中子C退速度："0200090032331501",开模联动："020009003333C300", 这四个值先暂时取出，看情况，再往里面添加。
        #
        # 2位小数的
        c = ["0200090033339B00", "0200090033339C00", "020009003033EC01", "0200090032335202",
             "0200090032335602", "0200090032335A02", "0200090032335E02", "0200090032336202",
             "0200090032336602", "0200090033337400", "020009003233B800",
             "0200090032336A00", "020009003233AE01", "020009003233AF01", "020009003233C700",
             "020009003233D600", "020009003233E700", "020009003233F600", "0200090032330701",
             "0200090032331601", "0200090033331200"
             ]  # 磨具冷却时间 "020009003233BA00",要在第二条开机数据中取开模4段速度，先去掉。看情况要不要取磨具冷却时间。

        # 16进制直接转换为10进制的
        d = ["0200090033339000", "0200090033339300", "0200090033339800", "0200090033331000",
             "0200090033331600", "0200090033331C00", "0200090033332200", "0200090033332800",
             "0200090033332E00", "0200090032335002", "0200090032335402", "0200090032335802",
             "0200090032335C02", "0200090032336002", "0200090032336402",
             "0200090032337802", "0200090032338000", "0200090032338300",
             "0200090032338600", "0200090032338900", "0200090032338C00", "020009003333B000",
             "020009003333B300", "020009003333B600", "020009003333B900", "020009003333BC00",
             "0200090032335000", "0200090032335100", "0200090032335400", "0200090032335500",
             "0200090032335800", "0200090032335900", "0200090032335C00", "0200090032335D00",
             "0200090032336000", "0200090032336100", "0200090033331001", "020009003233A001",
             "020009003233A301", "020009003233A601", "020009003233A901", "020009003233AD01",
             "020009003233C500", "020009003233C800", "020009003233D400", "020009003233D700",
             "020009003233E500", "020009003233E800", "020009003233F400", "020009003233F700",
             "0200090032330501", "0200090032330801", "0200090032331401", "0200090032331701",
             ]
        # frame_bytes 是 2568 位  其中02是帧头  03是帧尾   05 01 33 33 00 00 是行标识

        # 0~4   4~8      8~12
        # 8 9   10 11    12 13   14 15   16 17   18 19   20 21      。。。    2566 2567
        # 0 1   2   3    4   5   6   7   8   9   10  11  12  13        减去8
        #   1       2        3       4       5       6       7      。。。         1280   加1 除以二
        # 0001   0002     0003    0004    0005    0006    0007      。。。         0500
        frame_bytes = frame_bytes[28:-4]
        list_B = [i for i in range(16, 51)] + [i for i in range(176, 191)]
        aa = [int(str(i[-4:])[-2:] + str(i[-4:])[:-2], 16) for i in a]
        bb = [int(str(i[-4:])[-2:] + str(i[-4:])[:-2], 16) for i in b]
        cc = [int(str(i[-4:])[-2:] + str(i[-4:])[:-2], 16) for i in c]
        dd = [int(str(i[-4:])[-2:] + str(i[-4:])[:-2], 16) for i in d]
        for i in list_B:
            try:
                hangbiaoshi_4 = i
                corresponding_fields_i = frame_bytes[(i - 1) * 4:i * 4]
                if hangbiaoshi_4 in dd:  # 普通的
                    set_field_dictionary[{int(str(k[-4:])[-2:] + str(k[-4:])[:-2], 16): k for k in d}[hangbiaoshi_4]] = int(
                        str(corresponding_fields_i)[-2:] + str(corresponding_fields_i)[:-2], 16)
                elif hangbiaoshi_4 in aa:  # 分种类的
                    hangbiaoshi = {int(str(k[-4:])[-2:] + str(k[-4:])[:-2], 16): k for k in a}[hangbiaoshi_4]
                    if hangbiaoshi == "0200090032337A02":
                        set_field_dictionary[hangbiaoshi] = {"0000": "位置", "0001": "时间", "0002": "压力"}[
                            corresponding_fields_i]
                    elif hangbiaoshi == "0200090032338F00":
                        set_field_dictionary[hangbiaoshi] = {"0000": "不用", "0001": "使用"}[
                            corresponding_fields_i]
                    elif hangbiaoshi == "020009003333C300":
                        set_field_dictionary[hangbiaoshi] = \
                            {"0000": "不用", "0001": "托模", "0002": "中子A", "0003": "中子B", "0004": "中子C", "0005": "中子D",
                             "0006": "中子E", "0007": "中子F", "0008": "中子G", "0009": "中子H"}[corresponding_fields_i]
                    elif hangbiaoshi == "0200090033331501":
                        set_field_dictionary[hangbiaoshi] = {"0000": "储料后", "0001": "冷却后"}[
                            corresponding_fields_i]
                    elif hangbiaoshi == "020009003233AC01":
                        set_field_dictionary[hangbiaoshi] = {"0000": "停留", "0001": "定次", "0002": "振动"}[
                            corresponding_fields_i]
                    elif hangbiaoshi in ["020009003233C000", "020009003233E000", "0200090032330001"]:
                        set_field_dictionary[hangbiaoshi] = {"0000": "不用", "0001": "中子", "0002": "绞牙"}[
                            corresponding_fields_i]
                    elif hangbiaoshi in ["020009003233C200", "020009003233E200", "0200090032330201"]:
                        set_field_dictionary[hangbiaoshi] = {"0000": "行程", "0001": "时间", "0002": "行程+时间"}[
                            corresponding_fields_i]
                    elif hangbiaoshi in ["020009003233C300", "020009003233E300", "0200090032330301"]:
                        set_field_dictionary[hangbiaoshi] = {"0000": "关始", "0001": "中途", "0002": "关终"}[
                            corresponding_fields_i]
                    elif hangbiaoshi in ["020009003233C100", "020009003233E100", "0200090032330101"]:
                        set_field_dictionary[hangbiaoshi] = {"0000": "保持", "0001": "不保持"}[
                            corresponding_fields_i]
                    elif hangbiaoshi in ["020009003233D100", "020009003233F100", "0200090032331101"]:
                        set_field_dictionary[hangbiaoshi] = {"0000": "行程", "0001": "时间", "0002": "行程+时间"}[
                            corresponding_fields_i]
                    elif hangbiaoshi in ["020009003233D200", "020009003233F200", "0200090032331201"]:
                        set_field_dictionary[hangbiaoshi] = {"0000": "开终", "0001": "中途", "0002": "开始"}[
                            corresponding_fields_i]

                elif hangbiaoshi_4 in bb:  # 1位小数的
                    hangbiaoshi = {int(str(k[-4:])[-2:] + str(k[-4:])[:-2], 16): k for k in b}[hangbiaoshi_4]
                    set_field_dictionary[hangbiaoshi] = round(int(str(corresponding_fields_i)[-2:] + str(corresponding_fields_i)[:-2], 16) / 10, 1)

                elif hangbiaoshi_4 in cc:  # 2位小数的
                    hangbiaoshi = {int(str(k[-4:])[-2:] + str(k[-4:])[:-2], 16): k for k in c}[hangbiaoshi_4]
                    set_field_dictionary[hangbiaoshi] = round(int(str(corresponding_fields_i)[-2:] + str(corresponding_fields_i)[:-2], 16) / 100, 2)
            except:
                continue

        return set_field_dictionary

    # 解析开机数据
    # 0205013333————设置字段信息（解析开机数据，2568位）
    @staticmethod
    def parsing_startup_data_C(frame_bytes, set_field_dictionary):

        # 1位小数的
        b = ["020009003234C000", "020009003234C100", "020009003234C200", "020009003234C300",
             "020009003234C400", "020009003234C500", "020009003234C600", "020009003234C700", "020009003234C800",
             "0200090033339100", "0200090033339400", "0200090033339900", "0200090033331100",
             "0200090033331400", "0200090033331700", "0200090033331A00", "0200090033331D00",
             "0200090033332000", "0200090033332300", "0200090033332600", "0200090033332900",
             "0200090033332C00", "0200090033332F00", "0200090032335102", "0200090032335502",
             "0200090032335902", "0200090032335D02", "0200090032336102", "0200090032336502",
             "0200090032338100", "0200090032338400", "0200090032338700", "0200090032338A00",
             "0200090032338D00", "020009003333B100", "020009003333B400", "020009003333B700",
             "020009003333BA00", "020009003333BD00", "0200090032335300", "0200090032335200",
             "0200090032335700", "0200090032335600", "0200090032335B00", "0200090032335A00",
             "0200090032335F00", "0200090032335E00", "0200090032336300", "0200090032336200",
             "0200090033331101", "0200090033331301", "0200090033331701", "0200090032336C00",
             "020009003233A201", "020009003233A101", "020009003233A501", "020009003233A401",
             "020009003233A801", "020009003233A701", "020009003233AB01", "020009003233AA01",
             "020009003233D500", "020009003233E600", "020009003233F500",
             "0200090032330601", "0200090032331501",
             ]  # 中子A进速先拿出来，"020009003233C600",

        frame_bytes = frame_bytes[28:-4]
        list_C = [i for i in range(192, 201)]
        bb = [int(str(i[-4:])[-2:] + str(i[-4:])[:-2], 16) for i in b]
        for i in list_C:
            hangbiaoshi_4 = i
            corresponding_fields_i = frame_bytes[(i - 1) * 4:i * 4]

            if hangbiaoshi_4 in bb:  # 1位小数的
                hangbiaoshi = {int(str(k[-4:])[-2:] + str(k[-4:])[:-2], 16): k for k in b}[hangbiaoshi_4]
                set_field_dictionary[hangbiaoshi] = round(
                    int(str(corresponding_fields_i)[-2:] + str(corresponding_fields_i)[:-2], 16) / 10, 1)

        return set_field_dictionary

    def cha_xun(self, jitai_code):
        try:
            with pymysql.connect(host='192.168.1.192', port=3306, user='root', password='Hengde123',
                                 db='python_machine',
                                 charset='utf8') as conn:
                with conn.cursor() as cur:
                    sql = "SELECT value FROM set_and_start_value WHERE jitai_code=%s"
                    cur.execute(sql, (jitai_code,))
                    result1 = cur.fetchone()
                    if result1:
                        return json.loads(result1[0])
                    else:
                        sql = "INSERT INTO set_and_start_value VALUES (%s, %s)"
                        params = (jitai_code, json.dumps({'a': 'a'}))
                        cur.execute(sql, params)
                        conn.commit()
                        return {'a': 'a'}
        except pymysql.MySQLError as e:
            logger.error(f"数据库查询失败: {e}")
            return "数据库查询失败,请检查数据库是否可以访问"  # 或者你可以抛出异常，或者返回一个特定的错误值
        except Exception as e:
            logger.error(f"cha_xun执行失败: {e}")
            return "数据库查询失败,请检查数据库是否可以访问"  # 或者你可以抛出异常，或者返回一个特定的错误值

    def update(self, set_dict, jitai_code):
        '''
        :param set_dict: 修改后的值
        :param jitai_code: 根据机台码修改数据库
        :return:
        '''
        try:
            with pymysql.connect(host='192.168.1.192', port=3306, user='root', password='Hengde123',
                                 db='python_machine',
                                 charset='utf8') as conn:
                with conn.cursor() as cur:
                    sql = "UPDATE set_and_start_value SET value=%s WHERE jitai_code=%s"
                    params = (json.dumps(set_dict), jitai_code)
                    cur.execute(sql, params)
                    conn.commit()
        except pymysql.MySQLError as e:
            logger.error(f"写入数据库失败: {e}")
            # 这里不需要手动调用rollback()，因为with语句会自动处理
        except Exception as e:
            logger.error(f"更新数据库时发生未知错误: {e}")
            # 同样，不需要手动调用rollback()，因为with语句会自动处理
